﻿layui.use(['form', 'table', 'http', 'popup', 'upload'], function () {
    var form = layui.form;
    var table = layui.table;
    var $ = layui.$;
    var popup = layui.popup;
    var http = layui.http;
    var upload = layui.upload;
    table.render({
        elem: '#dataTable',
        url: '/User/StudentList',
        height: 'full',
        page: true,
        skin: 'line',
        toolbar: '#toolbar',
        defaultToolbar: [{
            title: '刷新',
            layEvent: 'refresh',
            icon: 'layui-icon-refresh',
        }, 'filter', 'print', 'exports'],
        cols: [[
            { type: 'checkbox' },
            { field: 'userName', title: '用户名' },
            { field: 'realName', title: '姓名' },
            { field: 'genderStr', title: '性别' },
            { field: 'userStatusStr', title: '状态' },
            { field: 'blockDay', title: '天数' },
            { field: 'lastLoginTime', title: '登录时间' },
            { title: '操作', toolbar: '#row-bar' },
        ]],
        done: function (res, curr, count) {
            if (res.code === 1) {
                popup.toastError(res.msg);
            }
        }
    });

    // 表格上方的按钮
    table.on('toolbar(dataTable)', function (obj) {
        if (obj.event === 'add') {
            add();
        } else if (obj.event === 'refresh') {
            refresh();
        } else if (obj.event === 'batchRemove') {
            batchRemove();
        } else if (obj.event === 'modify') {
            modifyPasword();
        } else if (obj.event === 'status') {
            setStatus();
        }
        else if (obj.event === 'import') {
            importStudent();
        }
    });
    // 行 操作
    table.on('tool(dataTable)', function (obj) {
        if (obj.event === 'edit') {
            add(obj.data);
        }
    });

    /**
     * 新增或编辑
     * @param {any} row
     */
    function add(row) {
        var title = '新增用户';
        if (row) {
            title = '编辑用户';
        }
        layer.open({
            type: 2,
            title: title,
            shade: 0.1,
            btn: ['确定', '取消'],
            area: ['500px', '400px'],
            content: "/User/AddStudent",
            success: function (layero, index) {
                if (row) {
                    var iframeWin = $(layero).find("iframe")[0].contentWindow;
                    iframeWin.editInit(row);
                }
            },
            yes: function (index, layero) {
                var iframeWin = $(layero).find("iframe")[0].contentWindow;
                iframeWin.save();
            }
        });
    }
    $("#search").click(function () {
        refresh();
    });
    /**刷新 */
    function refresh() {
        var data = { userName: $("#userName").val() };
        var userStatus = Number($("#userStatus").val());
        if (userStatus > -1) {
            data.userStatus = userStatus;
        }
        table.reload('dataTable', {
            where: data,
            page: {
                curr: 1
            }
        });
    }

    /**删除 */
    function batchRemove() {
        var checkStatus = table.checkStatus('dataTable');
        if (checkStatus.data.length === 0) {
            popup.toastWarning("至少选择一项")
            return false;
        }
        layer.confirm("确认删除所选用户吗？", {
            icon: 3,
            title: '批量删除'
        }, function (index) {
            var loading = layer.load(2);
            var data = checkStatus.data.map(i => i.id);
            http.ajax({
                url: '/User/BatchRemoveStudent',
                data: { ids: data },
                success: function (res) {
                    layer.close(loading);
                    layer.close(index);
                    if (res.code === 0) {
                        popup.toastSuccess(res.msg)
                        refresh();
                    } else {
                        popup.toastError(res.msg)
                    }
                },
                error: function () {
                    layer.close(loading);
                    popup.toastError("请求失败，请稍后重试")
                }
            });
        })
    }
    /**设置状态 */
    function setStatus() {
        var checkStatus = table.checkStatus('dataTable');
        if (checkStatus.data.length === 0) {
            popup.toastWarning("至少选择一项")
            return false;
        }
        var url = "/User/SetStatus";
        var panelIndex = popup.panelWebBtn('设置状态', url, ['500px', '460px'], function () {
            var data = form.val("fromStatus");
            if (data.setUserStatus === '-1') {
                popup.toastWarning("请选择状态")
                return false;
            }
            data.ids = checkStatus.data.map(i => i.id);
            var loading = layer.load(2);
            http.ajax({
                url: url,
                data: data,
                success: function (res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        layer.close(panelIndex);
                        popup.toastSuccess(res.msg)
                        refresh();
                    } else {
                        popup.toastError(res.msg)
                    }
                },
                error: function () {
                    layer.close(loading);
                    popup.toastError("请求失败，请稍后重试")
                }
            });
        }, function () {
            form.on('select(setUserStatus)', function (data) {
                if (data.value === '1' || data.value === '5') {
                    $("#blockDay").val('');
                    $("#blockDay").attr("disabled", "disabled");
                } else {
                    $("#blockDay").removeAttr("disabled");
                }
            });
            form.render('select');
        });
    }
    /**修改密码 */
    function modifyPasword() {
        var checkStatus = table.checkStatus('dataTable');
        if (checkStatus.data.length === 0) {
            popup.toastWarning("至少选择一项")
            return false;
        }
        layer.prompt({
            title: '请输入密码',
        }, function (value, index, elem) {
            var loading = layer.load(2);
            var data = checkStatus.data.map(i => i.id);
            http.ajax({
                url: '/User/ModifyPasword',
                data: { ids: data, password: value },
                success: function (res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        layer.close(index);
                        popup.toastSuccess(res.msg)
                        refresh();
                    } else {
                        popup.toastError(res.msg)
                    }
                },
                error: function () {
                    layer.close(loading);
                    popup.toastError("请求失败，请稍后重试")
                }
            });
        });
    }

    /**导入 */
    function importStudent() {
        var url = "/User/Import";
        var panelIndex = popup.panelWebBtn('导入用户', url, ['700px', '360px'], function () {
        }, function () {
            upload.render({
                elem: '#upload',
                auto: false,
                url: '/User/UploadStudent/',
                bindAction: '.layui-layer-btn0',
                accept: 'file',
                acceptMime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                exts: 'xlsx',
                choose: function (obj) {
                    obj.preview(function (index, file, result) {
                        $("#file").val(file.name);
                    })
                },
                before: function (obj) {
                    layer.load(2);
                },
                done: function (res) {
                    layer.closeAll('loading');
                    if (res.code === 0) {
                        popup.toastSuccess(res.msg);
                        refresh();
                        layer.close(panelIndex);
                    } else if (res.code === 1) {
                        layer.close(panelIndex);
                        popup.toastError(res.msg);
                    } else if (res.code === 2) {
                        var html = '';
                        $.each(res.data, function (i, item) {
                            html += `第${item.rowIndex}行`
                            $.each(item.fieldErrors, function (j, obj) {
                                html += `${j}${obj}<br />`
                            });
                        });
                        layer.alert(html, { title: res.msg });
                    }
                }
                , error: function () {
                }
            });
        });
    }
});